package com.csms.security.service;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.csms.entity.StoreUser;
import com.csms.security.entity.CsmsUserDetails;
import com.csms.service.StoreUserService;
import lombok.AllArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.HashSet;
import java.util.Set;

/**
 * author: yj
 * Date: 2023-02-0116:23
 */
@Service
@AllArgsConstructor
public class CsmsUserDetailsService implements UserDetailsServices {

    private final StoreUserService storeUserService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        StoreUser user = storeUserService.getOne(Wrappers.<StoreUser>query().lambda()
                .eq(StoreUser::getUsername,username));

        if (user != null) {
            CsmsUserDetails csmsUserDetails = new CsmsUserDetails();
            BeanUtils.copyProperties(user, csmsUserDetails);

            Set<GrantedAuthority> authorities = new HashSet<>(); // 角色集合
            authorities.add(new SimpleGrantedAuthority("ROLE_ADMIN"));
            csmsUserDetails.setAuthorities(authorities);

            return csmsUserDetails;
        }
        else
        {
            throw new UsernameNotFoundException("用户名和密码错误!");
        }
    }

    @Override
    public UserDetails loadUserByUsername(String username, long type) throws UsernameNotFoundException {
        StoreUser user = storeUserService.getOne(Wrappers.<StoreUser>query().lambda()
                .eq(StoreUser::getUsername,username)
                .eq(StoreUser::getTenantId,type));

        if (user != null) {
            CsmsUserDetails csmsUserDetails = new CsmsUserDetails();
            BeanUtils.copyProperties(user, csmsUserDetails);

            Set<GrantedAuthority> authorities = new HashSet<>(); // 角色集合
            authorities.add(new SimpleGrantedAuthority("ROLE_ADMIN"));
            csmsUserDetails.setAuthorities(authorities);

            return csmsUserDetails;
        }
        else
        {
            throw new UsernameNotFoundException("用户名和密码错误!");
        }
    }
}
